#ifndef _TMC_2209_H
#define _TMC_2209_H
#include "driver/gptimer.h"

enum {
    TMC_DUMP = 0,
    TMC_SPEED = 1,
    TMC_TARGET,
    TMC_START,
    TMC_STOP,
    TMC_CMD,
};

typedef struct {
    uint8_t type;

    union data_u
    {
        char buf[48];
        uint64_t val;
    } data;
} tmc_queue_t;


/*梯形加减速相关变量*/
typedef struct 
{
	/*当前电机状态*/
	uint8_t  run_state ;
	/*旋转方向*/
	uint8_t  dir ;
	/*脉冲间隔*/
	uint32_t  step_delay;  
	/*减速位置*/
	int64_t  decel_start; 
	/*减速步数*/
	int64_t  decel_val;
	/*最小间隔*/
	int  min_delay;
	/*加速步数*/
	int64_t  accel_count;
    int64_t step_count; //已经走过的步数
}speedRampData;

/*/系统状态*/
struct GLOBAL_FLAGS 
{
	//当步进电机正在运行时，值为1
	unsigned char running:1;
	//当串口接收到数据时，值为1
	unsigned char cmd:1;
	//当驱动器正常输出时,值为1
	unsigned char out_ena:1;
};

struct stepmotorops {
    int (*init)(void);
    int (*set_pin)(int8_t step_pin, int8_t dir_pin, int8_t enable_pin);
    int (*set_speed)(uint32_t speed);
    int (*set_position)(uint64_t pos);
    int (*set_accel)(uint32_t accel);
};

struct StepMotorModule {
    int8_t step_pin;
    int8_t dir_pin;
    int8_t enable_pin;
    uint8_t type;
    bool inited;

    uint32_t speed;
    uint32_t accel;
    uint64_t tarpos;
    uint64_t curpos;
    uint64_t maxpos;

    uint64_t cal_cnt;

    gptimer_handle_t gptimer;

    //系统加减速参数
    speedRampData srd;
    //系统电机、串口状态
    struct GLOBAL_FLAGS status;

    struct stepmotorops ops;
};

extern QueueHandle_t tmc_queue;

void step_motor_init(void);
uint8_t get_cur_pos_per(void);
uint32_t get_speed(void);
uint32_t get_accel(void);
uint8_t get_tmc_status(void);
struct StepMotorModule *GetStepMotorModule(const char *name);
void send_queue_event(char *msg, int len);
void tmc_queue_prase(tmc_queue_t *q);
#endif